<template>
  <div>
    <div class="customer-container" v-loading.fullscreen.lock="loadingPage">
      <form @submit.prevent="submit" class="base-form" v-if="init" novalidate>
        <div class="page-title">
          <div class="title">
            <el-button
              type="primary"
              native-type="submit"
              :disabled="submitting || pending"
            >
              保存
            </el-button>
          </div>
        </div>
        <div
          class="buttons"
          style="width: 700px; padding: 10px 0 0 10px; margin: 22px auto 0"
        >
          <!-- <el-button @click="AddCustomer" type="primary">
            新建客户
          </el-button> -->
        </div>

        <customer-edit-form
          style="margin-bottom: 24px"
          :id="form.id"
          :is-create="isCreate"
          :fields="fields"
          :SaveCustomer="true"
          @CustomerInfo="CustomerClose"
          v-model="form"
          ref="form"
        />
      </form>
    </div>
    <div
      style="margin-top: 12px; padding-bottom: 30px"
      class="customer-container"
      v-loading.fullscreen.lock="loadingPage"
      v-if="init"
    >
      <template v-if="init">
        <div class="page-title">
          <div class="title">联系人信息</div>
        </div>

        <div class="form-builder">
          <div class="buttons">
            <el-button v-show="form.id" @click="AddContacts" type="primary">
              新建联系人
            </el-button>
          </div>

          <el-table
            style="border: 1px solid #ebeef5"
            :data="AssociatedData"
            border
            empty-text="暂无数据"
          >
            <el-table-column
              prop="name"
              label="联系人"
              align="center"
              width="200"
            ></el-table-column>
            <el-table-column prop="phone" label="电话" align="center">
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="scope">
                <div :key="Date.now()" class="cellClass">
                  <el-button @click="EditContact(scope.row)" type="text">
                    编辑
                  </el-button>
                  <el-button
                    v-if="scope.row.relationSource"
                    @click="DeleteWechat(scope.row)"
                    type="text"
                    style="color: #f56c6c !important"
                    >解除关联</el-button
                  >
                  <el-button
                    v-if="!scope.row.relationSource"
                    @click="CurrentWechat(scope.row)"
                    type="text"
                  >
                    {{
                      query.source === '"weChat"'
                        ? "关联当前微信"
                        : "关联联系人"
                    }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </div>
    <!-- 客户新增关联 -->
    <CorrelationDialog
      v-if="isCorrelation"
      :isClose="isCorrelation"
      :customerId="form.id"
      :conversationId="query.conversationId"
      @CustomerClose="CorrelationClose"
    />
    <!-- 添加、修改联系人 -->
    <edit-contact-dialog
      ref="EditContactDialog"
      :customer="customer"
      :is-phone-unique="isPhoneUnique"
      :original-value="selectedContact"
      @submit-success="SubmitSuccess"
      @Preservation="SubmitSuccess"
    />
  </div>
</template>

<script>
/* api */
import * as CustomerApi from "@src/api/CustomerApi.ts";
import * as CustomerContact from "@src/api/CustomerContact.js";
/* component */
import CustomerEditForm from "@src/modules/customer/components/CustomerEditForm.vue";
/* enum */
import TenantDataLimitSourceEnum from "@model/enum/TenantDataLimitSourceEnum";
import TenantDataLimitTypeEnum from "@model/enum/TenantDataLimitTypeEnum";
/* util */
import platform from "@src/platform";
import * as FormUtil from "@src/component/form/util";
import * as util from "@src/modules/customer/util/customer";
/* mixin */
import VersionMixin from "@src/mixins/versionMixin/index.ts";
import ThemeMixin from "@src/mixins/themeMixin/index.ts";
import { parse } from "@src/util/querystring";

import FormMixin from "@src/component/form/mixin/form";

import CorrelationDialog from "./components/CorrelationDialog.vue";
import EditContactDialog from "@src/modules/customer/view/operationDialog/EditContactDialog.vue";
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
let query;
export default {
  name: "customer-perfect-view",
  inject: ["initData"],
  mixins: [VersionMixin, ThemeMixin],
  data() {
    return {
      submitting: false,
      pending: false,
      loadingPage: false,
      form: {},
      init: false,
      auth: {},
      fieldInfo: [],
      // 联系人
      AssociatedForm: {
        conversationId: "",
        source: "",
        linkmanId: "",
        phoneNumber: "",
        wechatUserId: "",
      },
      AssociatCustomer: [
        {
          value: "",
          label: "",
        },
      ],
      AssociatedFormRules: {
        linkmanId: [
          {
            required: true,
            message: "请选择联系人",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { pattern: /^[1]([3-9])[0-9]{9}$/, message: "联系电话格式有误" },
        ],
      },
      // 联系人列表
      AssociatedData: [],
      customer: {},
      selectedContact: {},
      isCorrelation: false,
      query: {},
    };
  },
  computed: {
    action() {
      return this.initData.action;
    },
    editId() {
      return this.initData.id || "";
    },
    eventId() {
      return this.initData.eventId || "";
    },
    fields() {
      let originFields = this.fieldInfo || [];
      let sortedFields = originFields
        .sort((a, b) => a.orderId - b.orderId)
        .map((f) => {
          if (f.formType === "address" && f.isSystem) {
            f.isNull = this.initData.isAddressAllowNull ? 1 : 0;
          }
          // 客户名称长度单独处理
          if (f.fieldName === "name") {
            f.maxlength = 50;
          }
          return f;
        })
        .filter((f) => {
          return (
            f.fieldName !== "tags" ||
            (f.fieldName === "tags" && this.initData.isDivideByTag)
          );
        });
      return FormUtil.migration(sortedFields);
    },
    isCreate() {
      return this.action == "create";
    },
    isPhoneUnique() {
      return this.initData.isPhoneUnique;
    },
  },
  methods: {
    submit() {
      this.submitting = true;
      this.$refs.form
        .validate()
        .then((valid) => {
          this.submitting = false;
          if (!valid) return Promise.reject("validate fail.");
          
          let params = util.packToCustomer(
            this.fields,
            this.form,
            this.initData.tags
          );
          
          params = this.globalFormSubmissionDataProcessingHandler(this.fields, params)
          
          // IM创建客户带conversationId
          if (query.conversationId) {
            params.conversationId = +query.conversationId;
          }
          this.toggleLoading();
          console.log(params);
          if (params.id) {
            //走编辑
            this.updateMethod(params);
          } else {
            //走新增
            this.createMethod(params);
          }
          // if (this.action === "edit") {
          //   return this.updateMethod(params);
          // }
          // if (this.action === "createFromEvent") {
          //   return this.createCustomerForEvent(params);
          // }

          // this.createMethod(params);
        })
        .catch((err) => {
          console.error(err);
          this.toggleLoading(false);
        });
    },
    createCustomerForEvent(params) {
      this.$http
        .post("/event/customer/create", params)
        .then((res) => {
          let isSucc = res.succ;

          platform.notification({
            type: isSucc ? "success" : "error",
            title: `创建客户${isSucc ? "成功" : "失败"}`,
            message: !isSucc && res.message,
          });

          if (!isSucc) return;

          const params = {
            ...res.data,
            eventId: this.eventId,
          };

          delete params.latitude;
          delete params.longitude;

          this.$http
            .post("/event/update4CusInfo", params, false)
            .then((res) => {
              if (this.initData.goto === "eventView") {
                let id = window.frameElement.dataset.id;
                return this.$platform.closeTab(id);
                // return (window.location.href = `/event/view/${this.initData.eventId}`);
              }
              if (this.initData.goto === "createTask") {
                let id = window.frameElement.dataset.id;
                return this.$platform.closeTab(id);
                // return (window.location.href = `/event/convent2Task/jump?eventId=${this.initData.eventId}&flow=${this.initData.flow}`);
              }
            });
        })
        .catch((error) =>
          console.error(
            "edit CustomerEditView createCustomerForEvent error",
            error
          )
        )
        .finally(() => {
          this.toggleLoading(false);
        });
    },
    createMethod(params) {
      const CreateCustomerPromise = this.$http.post("/customer/create", params);

      this.checkNumExceedLimitAfterHandler(CreateCustomerPromise)
        .then((res) => {
          let isSuccess = Boolean(res.succ);

          platform.notification({
            type: isSuccess ? "success" : "error",
            title: `创建客户${isSuccess ? "成功" : "失败"}`,
            message: !isSuccess && res.message,
          });

          if (!isSuccess) return;

          this.reloadTab();
          window.location.href = `${this.$resourcePrefix}/customer/view/${res.data.customerId}`;
        })
        .catch((err) => {
          console.error("err", err);
        })
        .finally(() => {
          this.toggleLoading(false);
        });
    },
    updateMethod(params) {
      const remindCount = localStorage.getItem("customer_remind_count");
      params.attribute.remindCount = remindCount || 0;

      const UpdateCustomerPromise = this.$http.post(
        `/customer/update?id=${this.form.id}`,
        params
      );

      this.checkNumExceedLimitAfterHandler(UpdateCustomerPromise)
        .then((res) => {
          if (!res.succ) {
            return platform.notification({
              type: "error",
              title: "更新客户失败",
              message: res.message,
            });
          }

          let fromId = window.frameElement.getAttribute("fromid");
          this.$platform.refreshTab(fromId);

          // window.location.href = `/customer/view/${res.data || this.editId}`;
          let id = window.frameElement.dataset.id;
          return this.$platform.closeTab(id);
        })
        .catch((err) => {
          console.error("CustomerEditView ~ updateMethod ~ error", err);
        })
        .finally(() => {
          this.toggleLoading(false);
        });
    },
    reloadTab() {
      let fromId = window.frameElement.getAttribute("fromid");
      this.$platform.refreshTab(fromId);
    },
    toggleLoading(loading = true) {
      this.pending = loading;
      this.loadingPage = loading;
    },
    //请求联系人列表
    AssociatedSearchCustomer(params) {
      const pms = params || {};
      return this.$http
        .post("/api/elasticsearch/outside/es/linkman/list", pms)
        .then((res) => {
          if (!res || !res.result.l·ist) return;
          if (res.result.list) {
            res.list = res.result.list.map((customer) =>
              Object.freeze({
                label: customer.name,
                value: customer.id,
              })
            );
          }
          return res;
        })
        .catch((e) => console.error(e));
    },
    AssociatedCustomer(value) {
      this.AssociatCustomer = value;
      this.AssociatedForm.linkmanId = value[0].value || "";
    },
    // 新增客户
    AddCustomer() {
      // window.location = '/customer/create';
      let fromId = window.frameElement.getAttribute("id");

      // this.$platform.openTab({
      //   id: "customer_create",
      //   title: "新建客户",
      //   url: "/customer/create",
      //   reload: true,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateCustomer,
        reload: true,
        fromId,
      })
    },
    CustomerClose(info) {
      if (info) {
        let form = {};
        form = util.packToForm(this.fields, form, info.customerAddress);
        this.form = FormUtil.initialize(this.fields, form);
        // if (query.lmPhone) {
        //   this.form.lmPhone = query.lmPhone;
        // }
        for (let i in info) {
          if (
            Reflect.has(this.form, i) &&
            i !== "customerAddress"
          ) {
            this.form[i] = info[i];
          }
        }
        this.getContactList();
      }
    },
    // 联系人
    getContactList() {
      const params = {
        customerId: this.form.id,
        pageNum: 1,
        pageSize: 100,
      };
      CustomerContact.getContactList(params).then((res) => {
        if (res.code === 200) {
          this.AssociatedData = res.result.list;
        }
      });

      this.$http
        .get("/customer/get", { id: this.form.id })
        .then((res) => {
          if (res.status) return;
          this.customer = res.data;
        })
        .catch((err) =>
          console.error(
            "customer-detail-view fetchCustomer catch error /n",
            err
          )
        );
    },
    //添加联系人
    EditContact(contact) {
      this.selectedContact = contact;
      this.$nextTick(this.$refs.EditContactDialog.openDialog);
    },
    // 关联当前微信
    CurrentWechat(contact) {
      this.$confirm(
        query.source === '"weChat"'
          ? "确认将当前微信与该联系人关联？"
          : "确认与该联系人关联？",
        "",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.CurrentWechatHttp(contact);
        })
        .catch(() => {});
    },
    DeleteWechat(contact) {
      this.$confirm(
        query.source === '"weChat"'
          ? "确认将当前微信与该联系人解除关联？"
          : "确认将当前联系人解除关联？",
        "",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.DeleteWechatHttp(contact);
        })
        .catch(() => {});
    },
    CurrentWechatHttp(contact) {
      this.$http
        .post("/api/im/outside/im/user/relationLinkman", {
          conversationId: query.conversationId,
          source: query.source,
          linkmanId: contact.id,
          phoneNumber: contact.phone,
          wechatUserId: query.wechatUserId,
        })
        .then((res) => {
          if (res.code !== 0)
            return this.$platform.notification({
              title: "绑定失败",
              message: res.message || "",
              type: "error",
            });
          this.$platform.notification({
            title: "绑定成功",
            type: "success",
          });
          // 页面刷新，有后台脏数据问题，延迟请求
          setTimeout(() => {
            this.getContactList();
          }, 2000);
        })
        .catch((e) => console.error(e));
    },
    DeleteWechatHttp(contact) {
      this.$http
        .post("/api/im/outside/im/user/cancelRelationLinkman", {
          conversationId: query.conversationId,
          source: query.source,
        })
        .then((res) => {
          if (res.code !== 0)
            return this.$platform.notification({
              title: "解除失败",
              message: res.message || "",
              type: "error",
            });
          this.$platform.notification({
            title: "解除成功",
            type: "success",
          });
          // 页面刷新，有后台脏数据问题，延迟请求
          setTimeout(() => {
            this.getContactList();
          }, 2000);
        })
        .catch((e) => console.error(e));
    },
    SubmitSuccess() {
      this.getContactList();
    },

    CorrelationClose(Updata = false) {
      this.isCorrelation = false;
      if (Updata) {
        this.getContactList();
      }
    },
    // 新增联系人
    AddContacts() {
      this.selectedContact = {};
      this.$nextTick(this.$refs.EditContactDialog.openDialog);
    },
  },
  async mounted() {
    try {
      // 获取客户表单字段列表
      let result = await CustomerApi.getCustomerFields({ isFromSetting: true });
      if (result.succ) {
        this.fieldInfo = result.data.map((item) => {
          return item;
        });
      }
      // 权限数据
      this.auth = this.initData.auth || {};

      // 初始化默认值
      let form = {};
      if (this.initData.action === "edit" && this.initData.id) {
        // 处理编辑时数据
        this.loadingPage = true;
        let cusRes = await CustomerApi.getForEdit(this.initData.id);
        this.loadingPage = false;
        if (cusRes.status === 0) form = cusRes.data;
      } else {
        // 检查版本数量限制
        this.checkNumExceedLimitBeforeHandler &&
          this.checkNumExceedLimitBeforeHandler(
            TenantDataLimitSourceEnum.Customer,
            TenantDataLimitTypeEnum.Customer
          );
      }
      // 从事件新建客户
      if (this.initData.action === "createFromEvent") {
        form = this.initData.eventCustomer;
      }
      // 初始化解析表单数据
      form = util.packToForm(this.fields, form, this.initData.customerAddress);
      this.form = FormUtil.initialize(this.fields, form);
      query = parse(window.location.search) || {};
      if (query.lmPhone) {
        this.form.lmPhone = query.lmPhone;
      }
      this.query = query;
      console.log("query", query);
      this.init = true;
    } catch (error) {
      this.toggleLoading(false);
      console.error("CustomerEditView mounted error ", error);
    }
  },
  components: {
    [EditContactDialog.name]: EditContactDialog,
    [CustomerEditForm.name]: CustomerEditForm,
    "customer-select": {
      name: "customer-select",
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => [],
        },
        remoteMethod: Function,
        updateCustomer: Function,
        placeholder: String,
      },
      methods: {
        input(value) {
          this.$emit("input", value);
        },
      },
      render(h) {
        return (
          <base-select
            value={this.value}
            placeholder={this.placeholder}
            remoteMethod={this.remoteMethod}
            onInput={this.updateCustomer}
          />
        );
      },
    },
    CorrelationDialog: CorrelationDialog,
  },
};
</script>

<style lang="scss">
body {
  padding: 10px;
}
.form-builder {
  width: 700px;
  padding: 0;
  margin: 22px auto 0;
}
.customer-container {
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: #fff;
  border-radius: 4px;

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;
    display: flex;
    justify-content: space-between;

    .iconfont {
      font-size: 12px;
    }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }

  .form-builder {
    width: 700px;
    padding: 10px 0 0 10px;
    margin: 22px auto 0;

    .input-and-btn {
      display: flex !important;
      flex-flow: row nowrap;

      .form-item,
      .form-text,
      .form-select,
      .biz-team-select {
        flex: 1;
      }

      .base-dist-picker {
        padding-right: 0;
      }

      button {
        margin-left: 10px;
      }
    }
  }
}
.buttons {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}
::v-deep .el-table--border {
  border: 1px solid #ebeef5 !important;
}
.cellClass {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
// .cell {
//   background: #fafafa !important;
// }
</style>
